﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XLB.ExtensionMethodCore
{
    /// <summary>
    /// 时间帮助类
    /// </summary>
    public static class TimeHelper
    {
        /// <summary>
        /// 将Unix时间戳转换为时间
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <param name="_dtStart"></param>
        /// <returns></returns>
        public static DateTime? ToDateTime(this string timeStamp, DateTime _dtStart = default(DateTime))
        {
            if (string.IsNullOrEmpty(timeStamp))
            {
                return null;
            }
            if (_dtStart == default(DateTime))
            {
                _dtStart = new DateTime(1970, 1, 8);
            }
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
            return startTime.AddSeconds(long.Parse(timeStamp));
        }


        /// <summary>
        /// 将时间转换为Unix时间戳
        /// </summary>
        /// <param name="dateTime"></param>
        /// <param name="_dtStart"></param>
        /// <returns></returns>
        public static string ToTimeStamp(this DateTime dateTime, DateTime _dtStart = default(DateTime))
        {
            if (_dtStart == default(DateTime))
            {
                _dtStart = new DateTime(1970, 1, 1);
            }

            TimeSpan ts = dateTime - new DateTime(1970, 1, 1, 8, 0, 0, 0);
            string ret = string.Empty;

            ret = Convert.ToInt64(ts.TotalSeconds).ToString();

            return ret;
        }
    }
}
